<?php
/**
 * Created by PhpStorm.
 * User: kevin
 * Date: 15-6-17
 * Time: 下午5:55
 */
namespace Admin\Controller;
use Home\Controller\DepartmentModel;
use Home\Model\UserModel;
use Think\Controller;
class TaskController extends AdminController{
    //显示所有科技查新
    public function index(){
        $status = I('get.status');
        $xmmc = I('get.xmmc');
        $map=1;
        if($status==1){
            $map.=" and (department_id is NULL or department_id = 0)";
        }elseif($status==2){
            $map.=" and department_id > 0";
        }
        if($xmmc){
            $map.=" and xmmc like '%$xmmc%'";
        }
        $map .= " and process_id!=15";
        $task = M('Kjcx'); // 实例化User对象
        if(empty($map)){
            $list = $this->lists($task);
        }else{
            $list = $this->lists($task,$map);
        }
        $statusList = $task->field('process_id')->group('process_id')->select();
       /* $unit = M('Department')->select();
        $unit = self::getUnitNum($unit);*/
        $this->assign('statusList',$statusList);
        //$this->assign('unit', $unit);
        $this->assign('list',$list);
        $this->assign('status',$status);
        $this->assign('xmmc',$xmmc);
        $this->meta_title = '委托订单管理';
        if(isset($_GET['p'])){
            $num = ($_GET['p']-1)*10;
            $this->assign('num', $num);
        }
        $this->display('index');
    }

    /**
     * 订单指派机构列表
     */
    function appointUnit(){
        $id = I('id');
        if($id){
            $name = I('name');
            if($name){
                $map['name'] = array('LIKE',"%$name%");
            }
            $unit = $this->lists(M('Department'),$map,' ID ASC');
            $unit = self::getUnitNum($unit);
        }else{
            $this->error('参数错误');
        }
        $this->assign('id',$id);
        $this->assign('name',$name);
        $this->assign('_list', $unit);
        $this->meta_title = '委托订单指派';
        $this->display();
    }

    /**
     * 统计各个机构的任务数量
     * @param array $arr
     * @return array
     */
    function getUnitNum($arr = array()){
        if(!empty($arr)){
            $model = M('kjcx');
            foreach($arr as $k=>$v){
                $map['department_id'] = $v['id'];
                $arr[$k][num] =$model->where($map)->count();
            }
        }
        return $arr;
    }

    //显示未处理任务
    public function newList(){
        $map['status'] = 1;
        if(UID=='1'){
            $this->assign('admin',1);
            $list = D('Task')->where($map)->getAll();
        }else{
            $list = M('Task')->where($map)->select(array('uid'=>UID));
        }
        $this->assign('list',$list);
        $this->display();
    }
    /*
     * 日志查看
     */
    public function log(){
        if(UID == '1'){
            $list = M('Tasklog')->select();
        }else{
            $map['uid'] = UID;
            $list = M('Tasklog')->select();
        }
        $this->assign('list', $list);
        $this->display();
    }
    //处理指派任务
    public function step1(){
        if(IS_POST){

        }else{
            $map['status'] = 2;
            $list = M('Task')->where($map)->select();
            $this->assign('list',$list);
            $this->display();
        }
    }

    /*
     * 管理员指派任务页面
     * @id任务编号
     * @unit机构编号
     */
    public function call($id='',$unit=''){
        $Task = D('Kjcx')->call($id, $unit);
        if($Task){
            action_log('call_task','Task',$id,UID);
            $this->success('指派任务成功',U('Task/index'));
        }else{
            $this->error($Task->getError());
        }
    }

    /*
     * 撤销任务
     */
    public function callback($id){
        $Task = D('Kjcx');
        $res = $Task->callback($id);
        if($res){
            action_log('revoke_assign','Task',$id,UID);
            $this->success('撤销任务成功',U('Task/index'));
        }else{
            $this->error('撤销任务失败',U('Task/index'));
        }
    }

    //订单管理查看报告
    public function info(){
        $task = M('Kjcx')->find(I('id'));
        $this->assign('info', $task);
        $sqfj_arr=explode(',',$task['sqfj']);
        $sqfj_arr_new = array();
        //显示附件名称
        if(!empty($sqfj_arr))
        {
            foreach($sqfj_arr as $k=>$vo){
                if($vo != ''){
                    $m = M('Attachment')->where('id='.$vo)->field('id,title')->find();
                    $sqfj_arr_new[$k]['title'] = $m['title'];
                    $sqfj_arr_new[$k]['id'] = $m['id'];
                }
            }
        }
        if(I('tag'))
        {
            $this->assign('tag', intval(I('tag')));
        }
        $this->assign('sqfj_arr', $sqfj_arr_new);
        $upload_ids_arr=explode(',',$task['upload_ids']);
        $this->assign('upload_ids_arr', $upload_ids_arr);
        $this->display();
    }
    //查看文档下载
    public function down_file(){
//        $file_id=I("request.file_id");
//        $result=M('attachment')->find($file_id);
//        $down_file=$result['dir'].$result['title'];
//        $down = substr($down_file,1,strlen($down_file));
//        $file ='file:///'.$_SERVER['DOCUMENT_ROOT'].__ROOT__.$down;
//        $fp = fopen($result['dir'], 'rb');
//        if(!file_get_contents($fp)){
//            $this->error("没有文件",U('Task/index'));
//        }else{
//            $this->success('下载成功',U('Task/index'));
//        }
//        header('HTTP/1.1 200 OK');
//        header("Pragma: public");
//        header("Expires: 0");
//        header("Content-type: application/octet-stream");
//        header("Content-Length: ".filesize($file));
//        header("Accept-Ranges: bytes");
//        header("Accept-Length: ".filesize($file));
//        $ua = $_SERVER["HTTP_USER_AGENT"];
//        if(preg_match("/MSIE/", $ua)){
//            header('Content-Disposition: attachment; filename="'.time().'"');
//        }else if(preg_match("/Firefox/", $ua)){
//            header('Content-Disposition: attachment; filename*="utf8\'\'' . time() . '"');
//        }else{
//            header('Content-Disposition: attachment; filename="'.time().'"');
//        }
//        ob_end_clean();
//        fpassthru($fp);
//        $this->assign('down_file',$file);
//        $this->display();
        $file_id=$_GET['file_id'];
        if(empty($file_id)){
            $this->error("文件不存在跳转页面");
        }else{//如果要加登录条件，这里可以自己加
            $map['id'] = $file_id;
            $list=D('Attachment')->where($map)->select();
            if ($list == false) {//文件不存在，可以跳转到其它页面
                header('HTTP/1.0 404 Not Found');
                header('Location: .');
            } else {
                $file_name="./".$list[0]['dir'].$list[0]['title_r'];//需要下载的文件
                $file_name=iconv("utf-8","gb2312","$file_name");
                if(file_exists($file_name)){
                    $fp=@fopen($file_name,"r+");//下载文件必须先要将文件打开，写入内存
                    if(!file_exists($file_name)){//判断文件是否存在
                        $this->error('文件不存在！');
                    }
                    $file_size=filesize($file_name);//判断文件大小
                    //返回的文件
                    Header("Content-type: application/octet-stream");
                    //按照字节格式返回
                    Header("Accept-Ranges: bytes");
                    //返回文件大小
                    Header("Accept-Length: ".$file_size);
                    //弹出客户端对话框，对应的文件名
                    Header("Content-Disposition: attachment; filename=".$list[0]['title']);
                    //防止<span id="2_nwp" style="width: auto; height: auto; float: none;"><a id="2_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?c=news&cf=1001&ch=0&di=128&fv=16&jk=208efa6f3933ab0f&k=%B7%FE%CE%F1%C6%F7&k0=%B7%FE%CE%F1%C6%F7&kdi0=0&luki=3&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=fab33396ffa8e20&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F971%2Ehtml&urlid=0" target="_blank" mpid="2" style="text-decoration: none;"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">服务器</span></a></span>瞬时压力增大，分段读取
                    $buffer=1024;
                    while(!feof($fp)){
                        $file_data=fread($fp,$buffer);
                        echo $file_data;
                    }
                    //关闭文件
                    fclose($fp);
                }else{
                    $this->error('文件不存在！');
                }

            }
        }
    }
    /**
     * 指派机构列表
     */
    public function appoint(){
        $id = I('id');
        if($id){
            $data = I('get.');
            //得到所有有审核的组
            $zu_arr = M('AuthGroup')->where('title like "%审核%"')->getField('id,title');
            $zu_str = join(',',array_keys($zu_arr));
            //查询所有机构的审核员
            $userModel = M('User');
            $map  = "typeid in ($zu_str)";
//            if($data['department']){
//                $map['department'] = $data['department'];
//            }
//            if($data['name']){
//                $map['name'] = array('LIKE',"%$data[name]%");
//            }
            $list = $this->lists($userModel,$map);
            foreach($list as $k=>$v){
                $where['sh_user_name'] = $v['id'];
                $list[$k]['num'] = M('kjcx')->where($where)->count();
            }
        }else{
            $this->error('参数错误');
        }
        $this->assign('_list',$list);
        $this->assign('id',$id);
        $this->assign('departmentList',getAllDepart());
        $this->assign('data',$data);
        $this->meta_title = '审核订单指派';
        $this->display();
    }

    /**
     * 审核订单列表
     */
    public function checkList(){
        $model = M('Kjcx');
        $data  = I('get.');
        $map   = 'process_id = 11';
        if($data['status']==1){
            $map .= ' AND sh_user_name IS NULL';
        }elseif($data['status']==2){
            $map .= ' AND sh_user_name >0';
        }
        if($data['xmmc']){
            $map .= ' AND xmmc LIKE "%'.$data[xmmc].'%"';
        }
        $list  = $this->lists($model,$map);
        $this->assign('_list',$list);
        $this->assign('data',$data);
        $this->meta_title = '审核订单管理';
        if(isset($_GET['p'])){
            $num = ($_GET['p']-1)*10;
            $this->assign('num', $num);
        }
        $this->display('clist');
    }

    function goAppoint($id=0,$uid=0){
        if($id && $uid){
            $model = M('kjcx');
            $data['sh_user_name'] = $uid;
            $res = $model->where(array('id'=>$id))->save($data);
            if($res){
                $this->success('指派成功');
            }else{
                $this->error('指派失败');
            }
        }else{
            $this->error('参数错误');
        }
    }
}